<template>
  <div class="wrapper">
    <common-header :title="title"></common-header>
    <div class="form">
      <div class="name"
           border-bottom-1px>
        <div class="">商家名称：</div>
        <div class="name-content">{{name}}</div>
      </div>
      <div class="author"
           border-bottom-1px>
        <div class="">联系人：</div>
        <div class="name-content">{{userName}}</div>
      </div>
      <div class="phone"
           border-bottom-1px>
        <div class="">电话：</div>
        <input type="tel"
               class="input"
               ref="phone-input"
               placeholder="请输入联系电话">
      </div>
      <div class="people"
           border-bottom-1px>
        <div class="">人数：</div>
        <input type="text"
               class="input"
               ref="persons"
               placeholder="请输入预约人数(纯数字0-10)"
               maxlength="2">
      </div>
      <div class="time"
           border-bottom-1px>
        <div class="">时间：</div>
        <div class="year-time"
             border-1px
             @click="handlePickDate">{{currentDate.toLocaleDateString().replace(/\//g,"-")}}</div>
        <div class="am-pm"
             border-1px
             @click="handlePickAm">{{am}}</div>
        <van-popup v-model="show"
                   position="bottom"
                   :overlay="false">
          <van-datetime-picker v-model="currentDate"
                               type="date"
                               :min-date="minDate"
                               @cancel="onDateCancel"
                               @confirm="onDateConfirm" />
        </van-popup>
        <van-popup v-model="showTwo"
                   position="bottom"
                   :overlay="false">
          <van-picker show-toolbar
                      title="标题"
                      :columns="columns"
                      @cancel="onCancel"
                      @confirm="onConfirm" />
        </van-popup>

      </div>
      <div class="discount"
           border-bottom-1px>
        <div class="discount-wrap">
          <p class="discount-title">优惠券：</p>
          <p class="discount-desc"
             @click="handlePickDiscounts">请选择优惠券</p>
          <van-popup v-model="roll"
                     position="bottom"
                     :overlay="false">
            <div class="roll-enter">
              <div>选择优惠券</div>
              <div class="enter"
                   @click="handleEnter">确认</div>
            </div>
            <common-scroll class="scroll"
                           :data="newDisCounts">
              <div class="content-scroll">
                <van-radio-group v-model="radio">
                  <van-cell-group>
                    <van-cell clickable
                              @click="radio = `${parseInt(index)+1}`"
                              class="roll-cell"
                              v-for="(item, index) of newDisCounts"
                              :key="item.id">
                      <div class="mini-roll">
                        <div class="mini-top"
                             border-bottom-1px>
                          <span>￥</span>{{item.money}}</div>
                        <div class="mini-bottom">优惠券</div>
                      </div>
                      <div class="roll-desc">
                        <h3>{{item.coupon_title}}(满{{item.tap_amount}}使用)</h3>
                        <p>有效期：{{item.end_time.substring(0,10)}}</p>
                      </div>
                      <van-radio :name="`${parseInt(index)+1}`" />
                    </van-cell>
                  </van-cell-group>
                </van-radio-group>
              </div>
            </common-scroll>

          </van-popup>
        </div>
      </div>
      <div class="remark">
        <div class="remark-title">备注</div>
        <textarea name=""
                  id=""
                  ref="textarea"
                  maxlength="140"></textarea>
      </div>
      <div class="button-wrap">
        <button @click.prevent="handleSubmit">提交</button>
      </div>
    </div>
  </div>
</template>

<script>
import CommonHeader from 'common/header/Header'
import CommonScroll from 'common/scroll/Scroll'
import { mapState } from 'vuex'
import { Toast } from 'vant'
import { isLogin } from '@/assets/js/isLogin'
export default {
  name: 'MerchantOrder',
  components: {
    CommonHeader,
    CommonScroll
  },
  computed: {
    name () {
      return this.$route.query.name
    },
    userName () {
      const userName = this.$localStorage.get('userName')
      if (userName != null) {
        return userName
      } else {
        return ''
      }
    },
    ...mapState(['disCounts'])
  },
  data () {
    return {
      title: '预约',
      columns: ['上午', '中午', '下午'],
      currentDate: new Date(),
      minDate: new Date(),
      show: false,
      showTwo: false,
      am: '上午',
      roll: false,
      radio: '1',
      disCountsArray: [],
      newDisCounts: []
    }
  },
  methods: {
    initDisCounts () {
      if (this.disCountsArray.length === 0) {
        return
      }
      let s = this.disCountsArray.reduce((prev, current) => {
        prev.push(Object.assign({}, this.disCounts.find((item) => {
          return current.coupon_id === item.id
        }), { member_coupon_id: current.member_coupon_id }))
        return prev
      }, [])
      this.newDisCounts = s
    },
    isNonEmpty (el, errorMsg) {
      return el.value === '' ? errorMsg : void 0
    },
    isNumber (el, errorMsg) {
      if (/^[0-9]*$/.test(el.value) && parseInt(el.value) > 0 && parseInt(el.value) < 10) {
        return void 0
      } else {
        return errorMsg
      }
    },
    isMoblie (el, errorMsg) {
      return !/^1(3|5|7|8|9)[0-9]{9}$/.test(el.value) ? errorMsg : void 0
    },
    handleEnter () {
      this.roll = false
    },
    handleSubmit () {
      const phone = this.$refs['phone-input']
      const persons = this.$refs.persons
      const userName = this.userName === ''
      const PhoneErrMsg = this.isNonEmpty(phone, '电话号码不能为空')
      const PhoneErrMsg2 = this.isMoblie(phone, '电话号码格式不正确')
      const personsErrMsg = this.isNonEmpty(persons, '人数不能为空')
      const personsErrMsg2 = this.isNumber(persons, '人数格式不正确')
      if (PhoneErrMsg || PhoneErrMsg2) {
        Toast({
          message: '电话号码输入错误',
          duration: 1000,
          forbidClick: true
        })
      } else if (personsErrMsg || personsErrMsg2) {
        Toast({
          message: '人数输入有误',
          duration: 1000,
          forbidClick: true
        })
      } else if (userName) {
        Toast({
          message: '联系人不能为空，请登录之后尝试',
          duration: 1000,
          forbidClick: true
        })
      } else {
        const appointmentDay = this.currentDate.toLocaleDateString().replace(/\//g, '-')
        const appointmentTime = this.am
        const contact = this.userName
        const desc = this.$refs.textarea.innerHTML
        const memberCouponId = this.newDisCounts.length > 0 ? this.newDisCounts[parseInt(this.radio) - 1].member_coupon_id : ''
        const sellerId = this.newDisCounts.length > 0 ? this.newDisCounts[parseInt(this.radio) - 1].seller_id : ''
        const overallNumber = this.$refs.persons.innerHTML
        const mobile = this.$refs['phone-input'].innerHTML
        this.$api.reserve.postReserve({
          appointment_day: appointmentDay,
          appointment_time: appointmentTime,
          contact,
          desc,
          member_coupon_id: memberCouponId,
          seller_id: sellerId,
          overall_number: overallNumber,
          mobile
        })
          .then(this.postReserveSucc)
          .catch((e) => {
            console.log(e)
          })
      }
    },
    postReserveSucc (res) {
      res = res.data
      if (res.code === this.$api.CODE_OK && res.data) {
        const msg = res.msg
        Toast({
          message: msg,
          duration: 1000,
          forbidClick: true
        })
      } else {
        const msg = res.msg
        Toast({
          message: msg,
          duration: 1000,
          forbidClick: true
        })
      }
    },
    handlePickDate () {
      this.show = true
    },
    handlePickAm () {
      this.showTwo = true
    },
    onConfirm (value, index) {
      this.am = value
      this.showTwo = false
    },
    onCancel () {
      this.showTwo = false
    },
    onDateConfirm (value, index) {
      this.show = false
    },
    onDateCancel () {
      this.show = false
    },
    handlePickDiscounts () {
      const sellerId = this.$route.params.id
      this.roll = true
      this.$api.discounts.getAllDiscounts({ seller_id: sellerId })
        .then(this.getAllDiscountsSucc)
        .catch((e) => {
          console.log(e)
        })
    },
    getAllDiscountsSucc (res) {
      res = res.data
      if (res.code === this.$api.CODE_OK && res.data) {
        const data = res.data
        this.disCountsArray = data
        this.initDisCounts()
      } else {
        const path = this.$route.path
        this.$localStorage.remove('loginStatus')
        this.$localStorage.remove('loginDate')
        Toast({
          message: '请重新登录',
          duration: 1000,
          forbidClick: true
        })
        isLogin(path)
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~stylus/variable.styl'
@import '~stylus/mixins.styl'

.wrapper>>>.van-popup--bottom
  max-height 100%
  height 100%

.wrapper >>> .van-picker__toolbar
  height 50px
  line-height 50px

.wrapper >>> .van-picker-column__item--selected
  font-size $fzThird

.wrapper >>> .van-cell__value--alone
  display flex
  justify-content space-between
  align-items center

.wrapper >>> .van-radio
  margin-left 62px
  width 50px
  height 50px

.wrapper >>> .van-radio .van-icon-checked
  color #FF4749

.wrapper>>>.van-radio .van-icon
  font-size $largeFz

.wrapper
  background-color $bgcWh
  position absolute
  left 0
  right 0
  top 0
  bottom 0
  touch-action none
  z-index 5

  .name, .author, .phone, .people, .time, .remark-title
    display flex
    justify-content space-between
    align-items center
    font-size $fzThird
    color $graySecond
    line-height 93px
    white-space nowrap
    padding()

    .input
      border none
      font-size $fzThird
      color $graySecond
      padding-right 10px
      box-sizing border-box
      width 80%

    .year-time
      display flex
      justify-content center
      align-items center
      padding 10px
      box-sizing border-box
      height 60px
      width 300px
      text-align center

    .am-pm
      display flex
      justify-content center
      align-items center
      padding 10px
      box-sizing border-box
      height 60px
      width 200px
      text-align center

  .name
    .name-content
      color $fzColor
      width 355px
      ellipsis()

  .discount
    justify-content space-between
    font-size $fzThird
    color $graySecond
    height 93px
    padding()

    .discount-wrap
      height 100%
      display flex
      align-items center
      justify-content space-between

      .discount-desc
        color $fzColor

      .roll-enter
        width 100%
        height 95px
        background rgba(245, 245, 245, 1)
        border-radius 30px 30px 0px 0px
        color $fzColor
        display flex
        justify-content space-between
        padding()
        align-items center
        font-size $smallFz

        .enter
          color #FF4749

      .scroll
        top 95px
        height 100%
        padding-bottom 100px
        box-sizing border-box

      .roll-cell
        height 130px
        width 100%
        display flex
        justify-contnet space-between

        .mini-roll
          width 146px
          height 83px
          background-color #FF4749
          margin-left 36px
          margin-right 30px
          position relative
          padding-left 7px
          padding-right 7px
          box-sizing border-box

          &:before
            content ''
            position absolute
            width 99%
            height 100%
            border 5px dotted $bgcWh
            top -5px
            left -5px
            z-index 1

        .mini-top
          width 100%
          height 50%
          font-size $fzThird
          color $whiteFzClor
          display flex
          justify-content center
          align-items center

          span
            font-size $smallFz

        [border-bottom-1px]
          border-color $bgcWh

        .mini-bottom
          width 100%
          height 50%
          font-size $smallFz
          color $whiteFzClor
          display flex
          justify-content center
          align-items center

        .roll-desc
          flex 1
          height 100%
          padding-top 33px
          box-sizing border-box

          h3
            font-size $fzThird
            width 100%
            color $fzColor
            display flex
            align-items center
            margin-bottom 10px
            font-weight normal

          p
            font-size $smallFz
            width 100%
            font-weight 500
            color #FF4749
            display flex
            align-items center

.remark
  margin-bottom 52px

  textarea
    width 100%
    height 294px
    background-color $bgHomeTitle
    border none
    outline none
    resize none
    padding()
    padding-top 20px
    padding-bottom 20px

.button-wrap
  height 90px
  width 100%
  box-sizing border-box
  padding-right 30px
  padding-left 30px

  button
    width 100%
    border none
    background-color $bgcOne
    color $whiteFzClor
    height 100%
    border-radius 8px
    font-size $fzOne
</style>
